# -*- coding:utf-8 -*-
# author: lkz
# date: 2015/12/01 10:33

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

DB = {
    'host': '10.73.17.247',
    'port': 3306,
    'user': 'sina',
    'password': 'sina',
    'db_name': 'auto_os_test'
}

DB_CONNECTION_STR = "mysql+pymysql://{user}:{password}@{host}:{port}/{db_name}?charset=utf8".format(**DB)

engine = create_engine(DB_CONNECTION_STR, pool_size=1, max_overflow=0)

db_session = scoped_session(
    sessionmaker(autocommit=False, autoflush=True, bind=engine)
)


# class get_session(object):
#     def __enter__(self):
#         self.session = scoped_session(
#             sessionmaker(autocommit=False, autoflush=True, bind=engine)
#         )
#
#         return self.session
#
#     def __exit__(self, exc_type, exc_value, traceback):
#         self.session.remove()

from contextlib import contextmanager


@contextmanager
def get_db_session():
    session = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=engine))
    yield session
    session.remove()
#
#

Base = declarative_base()
Base.query = db_session.query_property()
